package battleship;

import java.io.Serializable;

public class PlayerShip implements Serializable {
	private static final long serialVersionUID = 1L;

	/** An array of coordinates occupied by the ship. */
	final private int[][] occupied;
	/** hit[i] iff occupied[i] was hit. */
	final private boolean[] hit;
	/** The Ship that this object is based on. */
	final public Ship s;

	/**
	 * 
	 * @param s
	 *            The type of ship
	 * @param x
	 *            The x-value of the top-left corner of the ship
	 * @param y
	 *            The y-value of the top-left corner of the ship
	 * @param vertical
	 *            True iff length of the ship is parallel to the y-axis
	 */
	public PlayerShip(Ship s, int x, int y, boolean vertical) {
		this.s = s;
		occupied = new int[s.length][2];

		if (vertical) {
			for (int i = 0; i < s.length; i++) {
				occupied[i] = new int[] { x, y + i };
			}
		} else {
			for (int j = 0; j < s.length; j++) {
				occupied[j] = new int[] { x + j, y };
			}
		}

		hit = new boolean[occupied.length];
		for (int i = 0; i < hit.length; i++) {
			hit[i] = false;
		}
	}

	/**
	 * Return the number of hit points that the ship has left.
	 * 
	 * @return the number of hit points that the ship has left.
	 */
	public int getHealth() {
		int health = s.length;
		for (boolean b : hit) {
			if (b) {
				health--;
			}
		}
		return health;
	}

	/**
	 * Return the array of coordinates occupied by the ship.
	 * 
	 * @return the array of coordinates occupied by the ship.
	 */
	public int[][] getOccupiedCoords() {
		return occupied;
	}

	/**
	 * Register an attack at the given location, and return true iff the ship
	 * was hit.
	 * 
	 * @param x
	 *            the x-coordinate.
	 * @param y
	 *            the y-coordinate.
	 * @return true iff the ship was hit.
	 */
	public boolean isHit(int x, int y) {
		for (int i = 0; i < occupied.length; i++) {
			if (occupied[i][0] == x && occupied[i][1] == y) {
				hit[i] = true;
				return true;
			}
		}
		return false;
	}
}
